package xing.appwidget.bean

import android.content.Context
import android.content.pm.PackageInfo
import xing.appwidget.R
import xing.appwidget.storage.LabelStorageHelper
import xing.appwidget.utils.Utils
import java.util.*
import kotlin.ConcurrentModificationException
import kotlin.collections.ArrayList

data class PackageFilterParam constructor(var system: Boolean = true, var user: Boolean = true,
                                          var enabled: Boolean = true, var disabled: Boolean = true,
                                          var labels: Collection<String> = Collections.emptyList(), var initWithGrid: Boolean = false) {


    val isDefault = system && user && enabled && disabled && labels.isNullOrEmpty()

    fun isValid(packageInfo: PackageInfo): Boolean {
        val isSystemApp = Utils.isSystemApp(packageInfo)
        val appEnabled = packageInfo.applicationInfo.enabled
        val packageName = packageInfo.packageName

        val systemAppFilter = system and isSystemApp || user and !isSystemApp
        val enabledAppFilter = enabled and appEnabled || disabled and !appEnabled
        var inLabels = true
        for (label in labels) {
            inLabels = LabelStorageHelper.getPackageNameListByLabel(label).contains(packageName)
            if (inLabels) {
                break
            }
        }
        return systemAppFilter && enabledAppFilter && inLabels
    }

    fun toStrList(context: Context): List<String> {
        val list = ArrayList<String>()
        val resource = context.resources
        if (!system || !user) {
            if (system) {
                list.add(resource.getString(R.string.system))
            } else if (user) {
                list.add(resource.getString(R.string.user))
            }
        }
        if (!enabled || !disabled) {
            if (enabled) {
                list.add(resource.getString(R.string.enabled))
            } else if (disabled) {
                list.add(resource.getString(R.string.disabled))
            }
        }
        list.addAll(labels)
        return list;
    }
}